use serde::Deserialize;
// use serde_derive;
use lazy_static::lazy_static;
use toml;
//一定要一一对应不然映射要出现问题
/**
 * 参考链接：https://blog.csdn.net/xiaohuihui1400/article/details/130801880
*/
use std::fs::File;
use std::io::prelude::*;
const CONFFILE: &str = "config.toml";
#[derive(Debug, Deserialize)]
pub struct Database {
    pub user: Option<String>,
    pub pwd: Option<String>,
    pub name: Option<String>,
    pub host: Option<String>,
    pub port: Option<String>,
}
#[derive(Debug, Deserialize)]
pub struct Settings {
    pub database: Option<Database>,
}

impl Default for Settings {
    fn default() -> Self {
        let mut file = match File::open(CONFFILE) {
            Ok(f) => f,
            Err(e) => panic!("no such file {} exception:{}", CONFFILE, e),
        };
        let mut str_val = String::new();
        match file.read_to_string(&mut str_val) {
            Ok(s) => s,
            Err(e) => panic!("Error Reading file: {}", e),
        };
        toml::from_str(&str_val).unwrap()
    }
}
impl Settings {
    pub fn get<'a>() -> &'a Self {
        // 给静态变量延迟赋值的宏
        lazy_static! {
            static ref CACHE: Settings = Settings::default();
        }
        &CACHE
    }
}
// pub fn get_database() -> Database {
//     let mut file = match File::open(CONFFILE) {
//         Ok(f) => f,
//         Err(e) => panic!("no such file {} exception:{}", CONFFILE, e),
//     };
//     let mut str_val = String::new();
//     match file.read_to_string(&mut str_val) {
//         Ok(s) => s,
//         Err(e) => panic!("Error Reading file: {}", e),
//     };
//     println!("{:?}", &str_val);
//     let conf: Settings = toml::from_str(&str_val).unwrap();
//     println!("{:?}", &conf);
//     conf.database.unwrap()
// }
